﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Transactions;

namespace MySpiderMgr.Data.EF
{
    public class EFUnitOfWork : IUnitOfWork
    {
        static TransactionOptions transactionOptions = new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted };

        private TransactionScope _TransactionScope = null;

        readonly MyDbContext _db = null;

        public EFUnitOfWork()
        {
            this._db = new MyDbContext();
        }
        /// <summary>
        /// 保存
        /// </summary>
        public void Commit()
        {
            _db.SaveChanges();
            if (_TransactionScope != null)
            {
                _TransactionScope.Complete();
                _TransactionScope = null;
            }

        }
        public void BeginTran()
        {
            _TransactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions);
        }

        #region IDisposable Support
        private bool disposedValue = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _db.Dispose();
                }
                disposedValue = true;
            }
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);

            if (this._TransactionScope != null)
            {
                this._TransactionScope.Dispose();
                this._TransactionScope = null;
            }
        }
        #endregion


    }
}
